﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace library
{
    public static class Log
    {
        public delegate void LogHandler(string log);

        public static event LogHandler OnLog;

        public static void Write(string s)
        {
            lock ("data.txt")
            {
                File.AppendAllText("data.txt", string.Format("{0,2}:{1,2}.{2,1}    {3}\r\n", DateTime.Now.Minute, DateTime.Now.Second,
                            DateTime.Now.Millisecond, s));
            }

            if (OnLog != null)
                OnLog(
                    string.Format("{0,2}:{1,2}.{2,1}    {3}\r\n", DateTime.Now.Minute, DateTime.Now.Second,
                        DateTime.Now.Millisecond, s));

        }

        static internal void Add(string function, Peer peer, byte[] request)
        {
            Add(
                function,
                peer.Address,
                peer.EndPoint,
                request);
        }

        static internal void Add(string function, IPEndPoint IPEndPoint, byte[] request)
        {
            Add(function,
                new byte[Parameters.addressSize],
                IPEndPoint,
                request);
        }

        static void Add(string function, IEnumerable<byte> address, IPEndPoint IPEndPoint, byte[] request)
        {
            function = function.Substring(0, Math.Min(7, function.Length));

            string r = string.Empty;

            if (request != null)
            {
                r = string.Join(".", request.Take(request.Length - 2));

                if (r.Length > 22)
                {
                    r = string.Empty;
                    string s = string.Empty;

                    foreach (byte b in request.Take(request.Length - 2))
                    {
                        r += b.ToString() + ".";

                        if (r.Length > 20)
                        {
                            s += r + "\r\n\t\t\t\t\t\t  ";
                            r = string.Empty;
                        }
                    }
                    
                    s += r;
                    r = s;
                }

                if (request.Length > 2)
                    r += ":" + BitConverter.ToUInt16(request, request.Length - 2).ToString();
            }

            if (OnLog != null)
                OnLog(string.Format(
                    "{0}\t{1}\t{2}:{3}\t- {4}\r\n\r\n",
                        function,
                        string.Join(".", address).Substring(0, 16),
                        string.Join(".", IPEndPoint.Address.GetAddressBytes()),
                        IPEndPoint.Port,
                        r));
        }
    }
}
